package com.starblink.library.widget.wishlist

//import com.starblink.rocketreserver.MoveProduct2WishListMutation
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.config.PAGE_SIZE
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.library.widget.R
import com.starblink.library.widget.databinding.CellBoardWishlistBinding
import com.starblink.library.widget.databinding.DialogWishlistAddBinding
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.library.widget.wishlist.cell.BoardWishlistCell
import com.starblink.rocketreserver.FetchWishListsByAccountIdV2Query
import com.starblink.rocketreserver.MoveProductList2WishListMutation
import com.starblink.rocketreserver.fragment.WishListF
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.WishListsReq
//import com.starblink.rocketreserver.MoveProduct2WishListMutation
import kotlinx.coroutines.launch

/**
 *  添加至心愿单
 *  Create by yuanl at 2023/4/14
 **/
class WishlistAddBottomDialog : BaseBottomSheetFragment() {

    private lateinit var binding: DialogWishlistAddBinding

    private var batchPros: ArrayList<BatchProductArrEntry>? = null
    private var spmPageValue: Int = 0

    //    //弹窗类型 默认为1 单个操作 | 2 批量操作
//    private var dialogType = 1
    //请求成功是否隐藏toast
    private var isWishListPage = false

    private val data = arrayListOf<WishListF>()

    /**排除的心愿单ID，列表不显示它，默认为null*/
    private var excludeWishlistId: String? = null
    private var fromWishlistId: String? = null


    private val adapter by lazyOnNone {
        MutableAdapter(data).apply {
            addVhDelegate {
                BoardWishlistCell(
                    CellBoardWishlistBinding.inflate(
                        layoutInflater,
                        it,
                        false
                    )
                ) { toWishListId, name ->
                    move2Wishlist(toWishListId, name)
                }
            }
        }
    }

    private var pageNo = 1

    private val accountId = UserDataCenter.getAccountInfo()?.id
    private var lastId: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //弹窗类型
//        dialogType = arguments?.getInt(RoutePage.ARG.DIALOG_TYPE, 1) ?: 1
        batchPros = arguments?.getParcelableArrayList(RoutePage.ARG.BATCH_PRODUCT)
        isWishListPage = arguments?.getBoolean(RoutePage.ARG.IS_WISH_LIST, false) ?: false
        excludeWishlistId = arguments?.getString(RoutePage.ARG.EXCLUDE_WISHLIST_ID)
        fromWishlistId = arguments?.getString(RoutePage.ARG.WISH_ID)
//        spmPageValue = arguments?.getInt(RoutePage.ARG.SPM_PAGE_VALUE)?:0
        spmPageValue = SpmPageDef.Page_10211
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        binding = DialogWishlistAddBinding.inflate(layoutInflater)
        return super.onCreateDialog(savedInstanceState)
    }

    override fun getBindingRootView(): View = binding.root

    override fun initView() {
        setPeekPercent(650.0 / 812.0)
        binding.root.enableCorner(32.dp2px(), "top")
        binding.btnClose.setOnClickListener {
            dismiss()
        }
        binding.recycler.adapter = adapter
        binding.recycler.layoutManager = LinearLayoutManager(context)

        binding.refresher.justLoadMore {
            pageNo++
            loadData()
        }
        if (spmPageValue > 0) {
            binding.btnCreate.trackData(
                page = spmPageValue,
                element = SpmElementDef.WishListCreateClick,
                onlyHit = true
            )
        }
        binding.btnCreate.setOnClickListener {
            navigationTo(RoutePage.Wishlist.CREATE_BOARD) {
                withParcelableArrayList(RoutePage.ARG.BATCH_PRODUCT, batchPros)
                withBoolean(RoutePage.ARG.IS_WISH_LIST, isWishListPage)
                withString(RoutePage.ARG.WISH_ID, fromWishlistId)
            }
            dismiss()
        }
        loadData()
    }

    fun loadData() {
        accountId ?: return
        lifecycleScope.launch {
            var list = SkGqlClient.skQuery(
                FetchWishListsByAccountIdV2Query(
                    wishListsReq = WishListsReq(
                        accountId = accountId,
                        pageNo = pageNo.optional(),
                        pageSize = PAGE_SIZE.optional(),
                        lastId = Optional.present(if (pageNo == 1) null else lastId)
                    )
                ),
                showDefaultLoading = pageNo == 1,
            )?.data?.fetchWishListsByAccountIdV2
            list.let {
                if (!list?.wishLists.isNullOrEmpty()) {
                    list!!.wishLists!!.forEach { wsF ->
                        if (wsF.wishListF.id != excludeWishlistId) {
                            data.add(wsF.wishListF)
                        }
                        lastId = wsF.wishListF.id
                    }
                    adapter.refreshAll()
                    if (list.hasNext != true) {
                        binding.refresher.finishLoadMoreWithNoMoreData()
                    } else {
                        binding.refresher.finishLoadMore()
                    }
                } else {
//                    toastUI("No more data")
                }
                if (pageNo == 1 && list?.wishLists.isNullOrEmpty()) {
                    binding.vEmpty.visible()
                    binding.refresher.gone()
                }
            }
        }
    }

    private fun move2Wishlist(toWishListId: String, name: String) {
        if (batchPros.isNullOrEmpty()) {
            toast(CommUtils.getString(com.starblink.basic.style.R.string.network_error))
            return
        }
        lifecycleScope.launch {

            YYLogUtils.e("excludeWishlistId $excludeWishlistId ---> toWishListId $toWishListId")

            val data = SkGqlClient.skMutation(
                MoveProductList2WishListMutation(
                    items = arrayListOf<CollectItem>().apply {
                        batchPros!!.forEach {
                            add(
                                CollectItem(
                                    id = it.id,
                                    type = it.type.optional(),
                                )
                            )
                        }
                    }.optional(),
                    fromWishListId = if (excludeWishlistId.isNullOrBlank()) Optional.Absent else Optional.present(
                        excludeWishlistId!!
                    ),
                    toWishListId = toWishListId.optional(),
                ),
                showDefaultLoading = true,
            )
            val success = data?.data?.moveProductList2WishList == true
            if (success) {
                FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
                FlowBus.with<ArrayList<BatchProductArrEntry>>(FlowConst.WISHLIST_DETAILS_MOVE_SUCCESS)
                    .post(batchPros!!)
                if (!isWishListPage) {
                    toast(string(R.string.success_added_to_board).format(name))
                } else {
                    FlowBus.with<String>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_2)
                        .post(name)
                }
                dismiss()
            } else {
                data?.errors?.getOrNull(0)?.message?.let {
                    toast(it)
                }
            }
        }
    }


    companion object {

        @JvmStatic
        fun showAddListDialog(
            context: Context,
            batchPros: ArrayList<BatchProductArrEntry>,
            fromWishlistId: String? = null,
            isWishListPage: Boolean = false,
            excludeWishlistId: String? = null,
            spmPageValue: Int = 0
        ) {
            (context as? AppCompatActivity?)?.let {
                LoginCheckInterceptor.check2Login(context) {
                    WishlistAddBottomDialog().apply {
                        arguments = bundleOf(
                            RoutePage.ARG.BATCH_PRODUCT to batchPros,
                            RoutePage.ARG.IS_WISH_LIST to isWishListPage,
                            RoutePage.ARG.EXCLUDE_WISHLIST_ID to excludeWishlistId,
                            RoutePage.ARG.SPM_PAGE_VALUE to spmPageValue,
                            RoutePage.ARG.WISH_ID to fromWishlistId,
                        )
                    }.show(it.supportFragmentManager, "WishlistAddBottomDialog")
                }
            }
        }

    }
}